﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

namespace Sinc.ERP.Application;

/// <summary>
/// 产品信息服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class ProductService : CustomBaseService, IDynamicApiController
{
    private readonly SqlSugarRepository<Product> _productRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public ProductService(SqlSugarRepository<Product> productRep, ISqlSugarClient sqlSugarClient)
    {
        this._productRep = productRep;
        this._sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 查询所有产品信息 🔍
    /// </summary>
    /// <returns></returns>
    [DisplayName("查询所有产品信息")]
    [ApiDescriptionSettings(Name = "dropdownData"), HttpPost]
    public async Task<IList<ProductOutput>> DropdownData()
    {
        return await this._productRep.AsQueryable().Select<ProductOutput>().ToListAsync();
    }

    /// <summary>
    /// 分页查询产品信息 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询产品信息")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<ProductOutput>> Page(PageProductInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _productRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Code.Contains(input.Keyword) || u.Name.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(input.SupplierId != null, u => u.SupplierId == input.SupplierId)
            .Select<ProductOutput>();
        var productList = await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
        var supplierList = this.SupplierService.DropdownData().Result;
        foreach (var product in productList.Items)
        {
            var supplier = supplierList.FirstOrDefault(x => x.Id == product.SupplierId);
            product.SupplierName = supplier?.Name ?? product.SupplierId.ToString();
        }
        return productList;
    }

    /// <summary>
    /// 获取产品信息详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取产品信息详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Product> Detail([FromQuery] QueryByIdProductInput input)
    {
        return await _productRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加产品信息 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加产品信息")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddProductInput input)
    {
        var entity = input.Adapt<Product>();
        if (await _productRep.IsAnyAsync(u => u.Code != null && u.Code == input.Code)) throw Oops.Oh("产品编码已存在");
        return await _productRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新产品信息 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新产品信息")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateProductInput input)
    {
        if (await _productRep.IsAnyAsync(u => u.Id != input.Id && u.Code != null && u.Code == input.Code)) throw Oops.Oh("产品编码已存在");
        var entity = input.Adapt<Product>();
        await _productRep.AsUpdateable(entity).ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除产品信息 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除产品信息")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteProductInput input)
    {
        var entity = await _productRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _productRep.FakeDeleteAsync(entity);   //假删除
        //await _productRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除产品信息 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除产品信息")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")] List<DeleteProductInput> input)
    {
        var exp = Expressionable.Create<Product>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _productRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();

        return await _productRep.FakeDeleteAsync(list);   //假删除
        //return await _productRep.DeleteAsync(list);   //真删除
    }

    /// <summary>
    /// 导出产品信息记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出产品信息记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageProductInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportProductOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExportData(list, "产品信息导出记录");
    }

    /// <summary>
    /// 下载产品信息数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载产品信息数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return this.ExportData(new List<ExportProductOutput>(), "产品信息导入模板");
    }

    private IActionResult ExportData(List<ExportProductOutput> list, string fileName)
    {
        var supplierList = this.SupplierService.DropdownData().Result;
        var stream = ExcelHelper.ExportTemplate(list, fileName, (worksheet, prop) =>
        {
            if (prop.Name == nameof(ExportProductOutput.SupplierName))
            {
                return supplierList.Count == 0 ? null : supplierList?.Select(x => x.Name).ToList();
            }
            return null;
        });
        return stream;
    }

    /// <summary>
    /// 导入产品信息记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入产品信息记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        var supplierList = this.SupplierService.DropdownData().Result;
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportProductInput, Product>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x =>
                    {
                        if (x.SupplierName.IsEmpty())
                        {
                            x.Error = "供应商不能为空";
                            return false;
                        }

                        var supplier = supplierList.FirstOrDefault(s => s.Name == x.SupplierName);
                        x.SupplierId = supplier?.Id;
                        if (!x.SupplierId.HasValue)
                        {
                            x.Error = "供应商无效";
                            return false;
                        }

                        return true;
                    }).Adapt<List<Product>>();

                    var storageable = _productRep.Context.Storageable(rows)
                            .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Code), "产品编码不能为空")
                            .SplitError(it => it.Item.Code?.Length > 50, "产品编码长度不能超过50个字符")
                            .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Name), "产品名称不能为空")
                            .SplitError(it => it.Item.Name?.Length > 100, "产品名称长度不能超过100个字符")
                            .WhereColumns(it => new { it.Code }).SplitError(it => it.Any(), "产品编码已存在")
                            .SplitInsert(_ => true)
                            .ToStorage();

                    if (rows.Any())
                    {
                        storageable.BulkCopy();
                        storageable.BulkUpdate();
                    }
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });

            return stream;
        }
    }
}
